import React, { useEffect, useState } from 'react';
import { useUrlSearchParams } from 'use-url-search-params';
import an58 from '@mmstudio/an000058';
import RightContainer from '../../components/rightcontainer';
import Pagination from '../../components/pagination';
import Search from '../../components/search';
import Jtitle from './jtitle';
import api from '../../atoms/api';
import { IData, Query as Q1, Result as R1 } from '../api/teacher/query.api';
import Add from './add';
import List from './list';

export default function Jcontent({
	initialquery,
	teachers,
	theteacherisqualifiedforthecurriculums
}: {
	initialquery: Q1;
	teachers: Pick<ITbteacherlist, 'teacher_id' | 'teachername'>[];
	theteacherisqualifiedforthecurriculums: Pick<ITbtheteacherisqualifiedforthecurriculum, 'coursename' | 'professionalname' | 'teachername' | 'teacher_id' | 'classgroup'>[];
}) {
	const [data, setdata] = useState<R1>({
		count: 0,
		data: []
	});
	const [query, setquery] = useState<Q1>(initialquery);
	const [, setParams] = useUrlSearchParams({}, { page: Number });
	async function reload(q: Q1) {
		setquery(q);
		setParams(q);
		const data = await an58<R1, Q1>(api['/api/teacher/query'], 'get', q);
		setdata(data);
	}
	useEffect(() => {
		void reload(query);
	}, []);
	return <>
		<Jtitle />
		<RightContainer>
			<Search<IData>
				pagesize={Number(query.pagesize)}
				service={api['/api/teacher/query']}
				initq={query.q}
				onChange={(v) => {
					setdata({
						count: v.count,
						data: v.data
					});
					setquery({
						q: v.q,
						page: v.page.toString(),
						pagesize: query.pagesize
					});
				}} />
			<Add teacher={teachers} teachers={theteacherisqualifiedforthecurriculums} />;
		</RightContainer>
		<List data={data.data} />
		<RightContainer>
			<Pagination
				current={Number(query.page || '1')}
				pageSize={Number(query.pagesize || '10')}
				showTitle
				total={data.count}
				onChange={(p, s) => {
					const q = {
						q: query.q,
						page: p.toString(),
						pagesize: s.toString()
					} as Q1;
					setquery(q);
					reload(q);
				}}
			/>
		</RightContainer>
	</>;
}
